package org.millioncall.yueyoga.admin.dao;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.millioncall.openplatform.common.PaginateParams;
import org.millioncall.openplatform.common.PaginatedList;
import org.millioncall.openplatform.common.StartLimitPairImpl;
import org.millioncall.openplatform.dao.PreparedQuery;
import org.millioncall.openplatform.dao.mybatis.MyBatisDAOHelper;
import org.millioncall.openplatform.dao.mybatis.PagableSqlSessionTemplate;

public class BaseDao {

	/**
	 * 获取sqlSession
	 * 
	 * @return
	 */
	private MyBatisDAOHelper mybatisDaoHelper;
	private static final int AFFECTED_ROW = 0;

	public PagableSqlSessionTemplate getPagableSqlSessionTemplate() {
		return mybatisDaoHelper.getPagableSqlSession();
	}

	/**
	 * 插入
	 * 
	 * @param statement
	 * @param map
	 * @return
	 */
	public int save(String statement, Map<String, Object> map) {
		if (StringUtils.isNotBlank(statement) && !map.isEmpty()) {
			return getPagableSqlSessionTemplate().insert(statement, map);
		}
		return AFFECTED_ROW;
	}

	/**
	 * 修改
	 * 
	 * @param statement
	 * @param map
	 * @return
	 */
	public int update(String statement, Map<String, Object> map) {
		if (StringUtils.isNotBlank(statement) && !map.isEmpty()) {
			return getPagableSqlSessionTemplate().update(statement, map);
		}
		return AFFECTED_ROW;
	}

	/**
	 * 删除
	 * 
	 * @param statement
	 * @param id
	 * @return
	 */
	public int deleteById(String statement, Integer id) {
		if (StringUtils.isNotBlank(statement) && id != null) {
			return getPagableSqlSessionTemplate().delete(statement, id);
		}
		return AFFECTED_ROW;
	}

	/**
	 * 查询
	 * 
	 * @param statement
	 * @param id
	 * @return
	 */
	public Object findById(String statement, Integer id) {
		if (StringUtils.isNotBlank(statement) && id != null) {
			return getPagableSqlSessionTemplate().selectOne(statement, id);
		}
		return null;
	}

	/**
	 * 分页查询
	 * @param statement
	 * @param map
	 * @param start
	 * @param limit
	 * @return
	 */
	public PaginatedList<Object> findInPage(String statement,
			Map<String, Object> map, int start, int limit) {
		if (StringUtils.isNotBlank(statement)) {
			PreparedQuery<Object> pq = getPagableSqlSessionTemplate().findAll(
					statement, map);
			PaginatedList<Object> pl = pq.list(new PaginateParams(
					new StartLimitPairImpl(start, limit)));
			return pl.size() > 0 ? pl : null;
		}
		return null;
	}

	public MyBatisDAOHelper getMybatisDaoHelper() {
		return mybatisDaoHelper;
	}

	public void setMybatisDaoHelper(MyBatisDAOHelper mybatisDaoHelper) {
		this.mybatisDaoHelper = mybatisDaoHelper;
	}
}
